package com.bappi.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

public class FileUtils {

	public static final File ROOT = Environment.getExternalStorageDirectory();

	public static final File getFile(Context context, String fileName) {
		return getFile(context, null, fileName);
	}

	public static final File getFile(Context context, String dir,
			String fileName) {
		File ret = null;
		try {

			// File file = new File(ROOT.getAbsolutePath()
			// + File.separator
			// + ((dir == null) ? Constants.APP_FILES_FOLDER
			// : Constants.APP_FILES_FOLDER + dir
			// + File.separator));

			File file = new File(ROOT,
					(dir == null) ? Constants.APP_FILES_FOLDER
							: Constants.APP_FILES_FOLDER + dir + File.separator);
			if (!file.exists()) {
				file.mkdirs();
				File nomedia = new File(file, ".nomedia");
				if (!nomedia.exists()) {
					File parent = nomedia.getParentFile();
					if (!parent.exists()) {
						parent.mkdirs();
					}
					nomedia.createNewFile();
				}
			}
			if ((file != null) && (fileName != null)) {
				ret = new File(file, fileName);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

	@SuppressWarnings("unchecked")
	public static void downloadAndExtractFile(Context context, String fileUrl,
			String dirName, Canceller canceller, DownloadAndUnzipListener dazl)
			throws Exception {
		String fileName = fileUrl.substring(fileUrl.lastIndexOf("/"));
		File outputFile = getFile(context, fileName);
		URL u = new URL(fileUrl);

		Log.i("DREG", fileUrl);
		Log.i("DREG", fileName);
		Log.i("DREG", outputFile.getAbsolutePath());

		HttpURLConnection c = (HttpURLConnection) u.openConnection();
		c.setConnectTimeout(5000);
		c.setRequestMethod("GET");
		c.connect();
		if (c.getResponseCode() == HttpURLConnection.HTTP_OK) {
			long length = c.getContentLength();
			InputStream in = c.getInputStream();
			FileOutputStream f = new FileOutputStream(outputFile);
			byte[] buffer = new byte[1024];
			int len1 = 0;
			long totalRead = 0;
			while ((!canceller.isCanclled()) && (len1 = in.read(buffer)) != -1) {
				if (len1 > 0) {
					f.write(buffer, 0, len1);
					totalRead = totalRead + len1;
					dazl.progress((int) ((totalRead * 100) / length));
				}
			}
			dazl.downloadedCompleted();
			f.close();
			in.close();
			c.disconnect();
			if (!canceller.isCanclled()) {
				ZipFile zipFile = new ZipFile(outputFile);
				Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zipFile
						.entries();
				FileOutputStream fos;
				InputStream is;
				int size = zipFile.size();
				int count = 0;
				while ((!canceller.isCanclled()) && entries.hasMoreElements()) {
					ZipEntry entry = entries.nextElement();
					if ((!entry.isDirectory())
							&& entry.getName().endsWith(".mp3")) {
						fos = new FileOutputStream(FileUtils.getFile(context,
								dirName, entry.getName()));
						is = zipFile.getInputStream(entry);
						while ((len1 = is.read(buffer)) != -1) {
							if (len1 > 0) {
								fos.write(buffer, 0, len1);
							}
						}
						fos.close();
						is.close();
					}
					count++;
					dazl.progress(count * 100 / size);
				}
				zipFile.close();
				dazl.unzippingCompleted();
			}
			outputFile.delete();
		} else {
			c.disconnect();
		}
	}

	public static void downloadFullSura(Context context, String fileUrl,
			int suraId, int count, Canceller canceller, DownloadListener dl)
			throws Exception {
		for (int i = 1; (i <= count) && (!canceller.isCanclled()); i++) {
			String fileName = String.format("%03d%03d.mp3", suraId, i);
			File outputFile = getFile(context, Integer.toString(suraId),
					fileName);
			if (!outputFile.exists()) {
				byte[] bytes = HttpUtils.getHttpGetByteArrayResponce(String
						.format(fileUrl, suraId, i));
				if (bytes != null) {
					FileOutputStream fos = new FileOutputStream(outputFile);
					fos.write(bytes);
					fos.close();
					dl.progress((int) ((i * 100) / count));
				}
			}else{
				dl.progress((int) ((i * 100) / count));
			}
		}
	}

	public static void downloadVerse(Context context, String fileUrl,
			int suraId, int verseNo) throws Exception {
		String fileName = String.format("%03d%03d.mp3", suraId, verseNo);
		byte[] bytes = HttpUtils.getHttpGetByteArrayResponce(String.format(
				fileUrl, suraId, verseNo));
		if (bytes != null) {
			File outputFile = getFile(context, Integer.toString(suraId),
					fileName);
			FileOutputStream fos = new FileOutputStream(outputFile);
			fos.write(bytes);
			fos.close();
		}
	}
}
